package com.linchong.xshop.service.impl;


import com.linchong.xshop.dao.ProductDao;
import com.linchong.xshop.dao.ProductImgDao;
import com.linchong.xshop.dto.ImageHolder;
import com.linchong.xshop.dto.ProductExecution;
import com.linchong.xshop.entity.Product;
import com.linchong.xshop.entity.ProductImg;
import com.linchong.xshop.enums.ProductStateEnum;
import com.linchong.xshop.exceptions.ProductOperationException;
import com.linchong.xshop.service.ProductService;
import com.linchong.xshop.util.FileUtil;
import com.linchong.xshop.util.ImageUtil;
import com.linchong.xshop.util.PageCalculator;
import com.linchong.xshop.util.PathUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

import java.io.InputStream;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Service
public class ProductServiceImpl implements ProductService {
	@Autowired
	private ProductDao productDao;
	@Autowired
	private ProductImgDao productImgDao;

	@Override
	public ProductExecution getProductList(Product productCondition, int pageIndex, int pageSize) {
		//将页码转换为数据库的行码，并调用dao层取回指定页码的商品列表
		int rowIndex = PageCalculator.calculateRowIndex(pageIndex,pageSize);
		List<Product> productList = productDao.queryProductList(productCondition,rowIndex,pageSize);
		//基于同样的查询条件返回该查询条件下商品总数
		int count = productDao.queryProductCount(productCondition);
		ProductExecution pe = new ProductExecution();
		pe.setProductList(productList);
		pe.setCount(count);

		return pe;
	}

	/*
	  *1.处理缩略图，获取缩略图相对路径并赋值给product
	  *2.向表tb_product中添加商品信息，获取productid
	  *3.结合productId批量处理商品详情图
	  *4.将商品详情图批量插入到product_img中
	  *
	 */
	@Override
	@Transactional
	public ProductExecution addProduct(Product product, ImageHolder thumbnail, List<ImageHolder> productImgHolderList) throws RuntimeException {
		//空值判断
		if(product != null && product.getShop() != null && product.getShop().getShopId()!= null ){

			//为商品设置默认属性
			product.setCreateTime(new Date());
			product.setLastEditTime(new Date());

			//默认为上架状态
			product.setEnableStatus(1);
			//如果商品缩略图不为空，则添加商品
			if(thumbnail != null){
				addThumbnail(product,thumbnail);
			}
			try{
				//创建商品信息
				int effectedNum = productDao.insertProduct(product);
				if(effectedNum <= 0){
					throw new ProductOperationException("创建商品失败");
				}
			}catch(Exception e){
				throw new ProductOperationException("创建商品失败"+e.toString());
			}
		}
		//如若商品详情图不为空则添加
		if(productImgHolderList != null && productImgHolderList.size() > 0){
			   addProductImgList(product,productImgHolderList);
		}

		  return new ProductExecution(ProductStateEnum.SUCCESS,product);

	}

	@Override
	public Product getProductById(Long productId) {
		return productDao.queryProductByProductId(productId);
	}


	/**
	 * @param product
	 * @param thumbnail
	 * @param productImgHolderList
	 * @return
	 * @throws ProductOperationException
	 */
	@Override
	@Transactional
	/*
	*
	* 1.如果缩略图参数有值，则处理缩略图
	* 如果原先存在的缩略图则先删除在添加新图，之后获取缩略图的相对路径并赋值给product
	* 2.若商品详情图列表参数有值，对商品详情图片列表进行同样的操作
	* 3.将tb_product_img下面的该商品的详情图信息全部删除
	* 4.更新tb_product和tb_product_img信息
	*
	* */
	public ProductExecution modifyProduct(Product product, ImageHolder thumbnail, List<ImageHolder> productImgHolderList) throws ProductOperationException {

		//空值判断
		if(product != null && product.getShop() != null && product.getShop().getShopId() != null) {
			//给商品设置上默认属性
			product.setLastEditTime(new Date());
			//若商品缩略图不为空且原有的缩略图不为空则删除原有的缩略图在添加
			if (thumbnail != null) {
				//先获取一遍原有信息，因为原来的信息里有原图片地址
				Product tempProduct = productDao.queryProductByProductId(product.getProductId());
				if (tempProduct.getImgAddr() != null) {
					ImageUtil.deleteFileOrPath(tempProduct.getImgAddr());
				}
				addThumbnail(product, thumbnail);
			}


			//如果有新存入的商品详情图，则将原先的删除，并添加新的图片
			if (productImgHolderList != null && productImgHolderList.size() > 0) {
				deleteProductImgList(product.getProductId());
				addProductImgList(product, productImgHolderList);
			}

			//更新商品信息
			try {

				int effectedNum = productDao.updateProduct(product);
				if (effectedNum <= 0) {
					throw new ProductOperationException("更新商品信息失败");
				}
				return new ProductExecution(ProductStateEnum.SUCCESS, product);
			} catch (Exception e) {
				throw new ProductOperationException("更新商品信息失败" + e.toString());
			}
		}else{
			return new ProductExecution(ProductStateEnum.EMPTY);
		}

	}

	private void deleteProductImgList(Long productId) {

		//根据productId获取原来的图片
		List<ProductImg> productImgList = productImgDao.queryProductImgList(productId);
		//删除原来的图片
		for(ProductImg productImg:productImgList){
			ImageUtil.deleteFileOrPath(productImg.getImgAddr());
		}
		//删除数据库中原来的图片的信息
		productImgDao.deleteProductImgByProductId(productId);
	}


	/**
	 * 添加缩略图
	 * @param product
	 * @param thumbnail
	 */
	private void addThumbnail(Product product,ImageHolder thumbnail){

		//获得基准路径
		String dest = PathUtil.getShopImagePath(product.getShop().getShopId());
		//路径下保存路径
		String thumbnailAddr = ImageUtil.generateThumbnail(thumbnail,dest);
		product.setImgAddr(thumbnailAddr);
	}


	private void addProductImgList(Product product,List<ImageHolder> productImgHolderList){

		//获取图片存储路径，直接存在相应商品的文件夹下
		String dest = PathUtil.getShopImagePath(product.getShop().getShopId());
		List<ProductImg> productImgList = new ArrayList<ProductImg>();

		//遍历图片一次去处理，并添加进入productImg实体类中
		for(ImageHolder productImgHolder:productImgHolderList){
			String imgAddr = ImageUtil.generateThumbnail(productImgHolder,dest);
			ProductImg productImg = new ProductImg();
			productImg.setImgAddr(imgAddr);
			productImg.setProductId(product.getProductId());
			productImg.setCreateTime(new Date());
			productImgList.add(productImg);
		}

		//如果确实有图片是需要添加的，执行批量添加操作
		if(productImgList.size() > 0){
			try{
				int effectedNum = productImgDao.batchInsertProductImg(productImgList);
				if(effectedNum <= 0){
					throw new ProductOperationException("创建商品详情图失败！");
				}
			}catch (Exception e){
               throw new ProductOperationException("创建商品详情图片失败！"+e.toString());
			}
		}
	}
//
//	@Override
//	public ProductExecution getProductList(Product productCondition, int pageIndex, int pageSize) {
//		int rowIndex = PageCalculator.calculateRowIndex(pageIndex, pageSize);
//		List<Product> productList = productDao.queryProductList(productCondition, rowIndex, pageSize);
//		int count = productDao.queryProductCount(productCondition);
//		ProductExecution pe = new ProductExecution();
//		pe.setProductList(productList);
//		pe.setCount(count);
//		return pe;
//	}

//	@Override
//	public Product getProductById(long productId) {
//		return productDao.queryProductByProductId(productId);
//	}
//
//	@Override
//	@Transactional
//	public ProductExecution addProduct(Product product, CommonsMultipartFile thumbnail,
//			List<CommonsMultipartFile> productImgs) throws RuntimeException {
//		if (product != null && product.getShop() != null && product.getShop().getShopId() != null) {
//			product.setCreateTime(new Date());
//			product.setLastEditTime(new Date());
//			product.setEnableStatus(1);
//			if (thumbnail != null) {
//			//	addThumbnail(product, thumbnail);
//			}
//			try {
//				int effectedNum = productDao.insertProduct(product);
//				if (effectedNum <= 0) {
//					throw new RuntimeException("创建商品失败");
//				}
//			} catch (Exception e) {
//				throw new RuntimeException("创建商品失败:" + e.toString());
//			}
//			if (productImgs != null && productImgs.size() > 0) {
//			//	addProductImgs(product, productImgs);
//			}
//			return new ProductExecution(ProductStateEnum.SUCCESS, product);
//		} else {
//			return new ProductExecution(ProductStateEnum.EMPTY);
//		}
//	}
//
//	@Override
//	@Transactional
//	public ProductExecution modifyProduct(Product product, CommonsMultipartFile thumbnail,
//			List<CommonsMultipartFile> productImgs) throws RuntimeException {
//		if (product != null && product.getShop() != null && product.getShop().getShopId() != null) {
//			product.setLastEditTime(new Date());
//			if (thumbnail != null) {
//				Product tempProduct = productDao.queryProductByProductId(product.getProductId());
//				if (tempProduct.getImgAddr() != null) {
//					FileUtil.deleteFile(tempProduct.getImgAddr());
//				}
//			//	addThumbnail(product, thumbnail);
//			}
//			if (productImgs != null && productImgs.size() > 0) {
//				deleteProductImgs(product.getProductId());
//			//	addProductImgs(product, productImgs);
//			}
//			try {
//				int effectedNum = productDao.updateProduct(product);
//				if (effectedNum <= 0) {
//					throw new RuntimeException("更新商品信息失败");
//				}
//				return new ProductExecution(ProductStateEnum.SUCCESS, product);
//			} catch (Exception e) {
//				throw new RuntimeException("更新商品信息失败:" + e.toString());
//			}
//		} else {
//			return new ProductExecution(ProductStateEnum.EMPTY);
//		}
//	}

//	private void addProductImgs(Product product, List<CommonsMultipartFile> productImgs) {
//		String dest = FileUtil.getShopImagePath(product.getShop().getShopId());
//		List<String> imgAddrList = ImageUtil.generateNormalImgs(productImgs, dest);
//		if (imgAddrList != null && imgAddrList.size() > 0) {
//			List<ProductImg> productImgList = new ArrayList<ProductImg>();
//			for (String imgAddr : imgAddrList) {
//				ProductImg productImg = new ProductImg();
//				productImg.setImgAddr(imgAddr);
//				productImg.setProductId(product.getProductId());
//				productImg.setCreateTime(new Date());
//				productImgList.add(productImg);
//			}
//			try {
//				int effectedNum = productImgDao.batchInsertProductImg(productImgList);
//				if (effectedNum <= 0) {
//					throw new RuntimeException("创建商品详情图片失败");
//				}
//			} catch (Exception e) {
//				throw new RuntimeException("创建商品详情图片失败:" + e.toString());
//			}
//		}
//	}

//	private void deleteProductImgs(long productId) {
//		List<ProductImg> productImgList = productImgDao.queryProductImgList(productId);
//		for (ProductImg productImg : productImgList) {
//			FileUtil.deleteFile(productImg.getImgAddr());
//		}
//		productImgDao.deleteProductImgByProductId(productId);
//	}



//	private void addThumbnail(Product product, CommonsMultipartFile thumbnail) {
//		String dest = FileUtil.getShopImagePath(product.getShop().getShopId());
//		String thumbnailAddr = ImageUtil.generateThumbnail(thumbnail, dest);
//		product.setImgAddr(thumbnailAddr);
//	}
}
